package com;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.net.Socket;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;

public class SSLServer {
	
	public SSLServer(){}
	
	private SSLServerSocket getSSLServerSocket(int port){
		SSLServerSocket s = null;
		try{
			String key = "C:\\Program Files\\Java\\jdk1.7.0_21\\bin\\SSLKey";
			char keyStorePass [] = "himitsu".toCharArray();
			char keyPassword [] = "himitsu".toCharArray();
			KeyStore kstore = KeyStore.getInstance("JKS");
			kstore.load(new FileInputStream(key), keyStorePass);
			KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
			kmf.init(kstore, keyPassword);
			
			SSLContext sslContext = SSLContext.getInstance("SSLv3");
			sslContext.init(kmf.getKeyManagers(), null, null);
			SSLServerSocketFactory sslFactory = sslContext.getServerSocketFactory();
			s = (SSLServerSocket) sslFactory.createServerSocket(port);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return s;
	}
	
	public static void main(String [] args){
		SSLServerSocket serverSocket = null;
		int port = 10080;
		try{
			SSLServer server = new SSLServer();
			serverSocket = server.getSSLServerSocket(port);
			System.out.println("SSLServer listening ...");
			while(true){
			
				Socket socket = serverSocket.accept();
				
				RequestHandler handler = new RequestHandler(socket);
				Thread thread = new Thread(handler);
				thread.start();
			}
		}catch (Exception e) {
			// TODO: handle exception
		}
	}

}

class RequestHandler implements Runnable {
	private Socket socket;
	
	public RequestHandler(){}
	
	public RequestHandler(Socket socket){
		this.socket = socket;
	}
	
	@Override
	public void run() {
		if(socket == null){ return; }
		try{
			//ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
			byte[] bytes = new byte[1024];
			StringBuffer sb = new StringBuffer();
			BufferedInputStream bis = new BufferedInputStream(this.socket.getInputStream());
			int i=0;
			while((i = bis.read(bytes)) != -1){
				sb.append(new String(bytes));
				bytes = null;
				bytes = new byte[1024];
			}
			System.out.println(sb.toString());
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
